<template>
    <div class="w-full h-100vh flex-center select-none">
        <div
            class="w-100 box-border p-20px flex flex-col items-center shadow-2xl"
        >
            <div class="font-size-18px">多时间序列数据预测平台后台管理系统</div>
            <div class="w-full my-20px flex flex-col gap-20px">
                <n-input
                    v-model:value="loginForm.account"
                    placeholder="账号"
                    size="large"
                    maxlength="9"
                />
                <n-input
                    v-model:value="loginForm.password"
                    placeholder="密码"
                    type="password"
                    show-password-on="click"
                    size="large"
                    maxlength="15"
                />
            </div>
            <n-button
                type="primary"
                size="large"
                class="w-full my-20px"
                :focusable="false"
                @click="handleLogin"
            >
                登录
            </n-button>
            <n-divider>
                <n-button
                    text
                    type="warning"
                    @click="router.push({ name: 'forget' })"
                >
                    忘记密码?
                </n-button>
            </n-divider>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { throttle } from "radash";
import { login, autoLogin } from "@/service/api/auth";

const router = useRouter();

const loginForm = reactive({
    account: "",
    password: "",
});

onMounted(async () => {
    if (sessionStorage.getItem("token")) {
        try {
            await autoLogin();
            router.replace({ path: "/" });
        } catch (err) {
            sessionStorage.clear();
            window.NMessage.error("登录失败，请重新登录");
        }
    }
});

const handleLogin = throttle({ interval: 2000 }, async () => {
    if (
        !/^[1-9]\d{8}$/.test(loginForm.account) ||
        !/^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{8,}$/.test(loginForm.password)
    ) {
        window.NMessage.warning("请输入正确的账号或密码");
        return;
    }
    try {
        await login(loginForm.account, loginForm.password);
        router.replace({ path: "/" });
    } catch (err) {
        window.NMessage.error((err as Error).message);
    }
});
</script>

<style scoped></style>
